package com.web.base.auth.dao;

import com.blue.jdbc.BaseDao;
import com.web.base.auth.model.Role;
import com.web.base.auth.model.RoleUser;
import com.web.base.user.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色－用户数据库访问
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年04月15日
 */
@Repository
public class RoleUserDao extends BaseDao<RoleUser>
{
	public RoleUserDao()
	{
	}
	
	@Override
	protected void query(StringBuilder sql, RoleUser param)
	{
		if (param != null)
		{
			if (param.getUserId() != null)
				sql.append(" and a.a.user_id=:userId");
			
			if (param.getRoleId() != null)
				sql.append(" and a.role_id=:roleId");
		}
	}
	
	public List<Role> listSelect(Integer userId)
	{
		Map<String, Object> param = new HashMap<>();
		param.put("userId", userId);
		String sql = "select r.id, r.name, r.app_id, isnull(ra.role_id) selected from auth_role r"
				+ " left join (select * from auth_role_user where user_id=:userId) ra on ra.role_id=r.id"
				+ " where r.state=0";
		return jdbcObjectTemplate.list(Role.class, sql, param);
	}

	public List<User> groupRole(List<Integer> userIdList)
	{
		String sql = "select ru.user_id id, GROUP_CONCAT(r.name) role_names" +
				" from auth_role_user ru inner join auth_role r on r.id=ru.role_id" +
				" where ru.user_id in (%s)" +
				"group by ru.user_id";
		return jdbcObjectTemplate.list(User.class, String.format(sql, StringUtils.join(userIdList, ",")));
	}
	
}
